package org.example.service.impl;

import com.alibaba.fastjson.JSON;
import org.example.entity.User;
import org.example.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    //作为一个家长学生软件，那么应该是每天都会使用，但是如果周六日有可能会放假
    //所以应该考虑最长为周六日，然后每次请求在拦截器末端都会延长时间至72小时
    @Override
    public void setUser(String token, User user) {
        stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(user),72, TimeUnit.HOURS);
    }

    @Override
    public User getUser(String token) {
        String s = stringRedisTemplate.opsForValue().get(token);
        User user = JSON.parseObject(s, User.class);
        return user;
    }

    @Override
    public void setToken(int userId, String token) {
        stringRedisTemplate.opsForValue().set(""+userId, JSON.toJSONString(token),72, TimeUnit.HOURS);
    }

    @Override
    public String getToken(int userId) {
        String s = stringRedisTemplate.opsForValue().get(""+userId);
        String token = JSON.parseObject(s, String.class);
        return token;
    }
    /**删除老的token以及其对应的身份认证信息**/
    @Override
    public void deleteToken(int userId) {
        String token = getToken(userId);
        if (token==null) return;
        stringRedisTemplate.delete(token);
        stringRedisTemplate.delete(""+userId);
    }
}
